package SmallClass

import (
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models/Admin"
	error2 "OnlineRetailers/models/errorDeal"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type UpdateSmallClass struct {
	beego.Controller
}

func (c *UpdateSmallClass) UpdateSmallClass() {

	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()

	var addr = "/SmallClass/UpdateSmallClass"
	var err error

	smallClass := &Admin.SmallClass{}
	class := []*Admin.Classification{}
	log := &error2.Log{}
	mes := &error2.Mes{}

	o := orm.NewOrm()

	err = json.Unmarshal([]byte(c.GetString("smallClass")), smallClass)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	err = json.Unmarshal([]byte(c.GetString("class")), &class)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	err = session2.CheckSession(c.Ctx.Request.Header["Session"], 0)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	err = DeleteClassM2M(o, smallClass.SmallClassId)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	smallClass.Classification = class
	fmt.Println(class)

	if len(smallClass.Classification) != 0 {
		err = PostClassM2M(o, smallClass)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "402", err, addr, err.Error())
			return
		}
	}
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "402", err, addr, err.Error())
		return
	}

	//fmt.Println(key)

	_, err = o.Update(smallClass)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "402", err, addr, err.Error())
		return
	}

	mes.Mes = "success"
	mes.Code = "200"
	c.Data["json"] = mes
}
